#! -*- coding: utf-8 -*-
import json

from script_utils import query, oid2nid
from script_utils import models

cols = {
    'locality': [
        'id',
        'site_id',
        'name',
        'name_en',
        'time_zone',
        'cover',
        'st_asgeojson(st_astext(location))',
        'itinerary_covers',
        'published',
        'position',
    ],
    'destination': [
        'id',
        'site_id',
        'locality_id',
        'name',
        'name_en',
        'is_departured',
        'published',
        'st_asgeojson(st_astext(location))',
        'last_modified',
        'date_added',
    ],
    'destination_option': [
        'id',
        'name',
        'description',
        'destination_id',
        'images',
        'is_active',
        'is_booked',
        'day',
        'user_id',
        'published',
        'last_modified',
        'date_added',
    ],
    'option_mtu': [
        'id',
        'mtu_id',
        'option_id',
        'section',
        'cover',
        'is_active',
        'last_modified',
        'date_added',
    ],
    "tinysite": [
        "target_id",
        "target_type"
    ],
    "tag": [
        "id",
        "name",
        "last_modified",
        "date_added",
    ],
    "destination_info": [
        "id",
        "destination_id",
        "max_days",
        "min_days",
        "percentage",
        "periphery",
        "images",
        "is_active",
        "last_modified",
        "date_added",
    ],
    "vacation_destinationinfo_tags": [
        "destinationinfo_id",
        "tag_id",
    ],
}


def get_tinysite_dict():
    from collections import defaultdict

    data = defaultdict(list)
    for row in query('aoyouji_tinysite', cols=cols['tinysite']):
        data[row[0]] = row[1]

    return data


tinysite_dict = get_tinysite_dict()


def get_desitinationinfo_tag(key="destination"):
    result = []
    col_key = 'vacation_destinationinfo_tags'
    for e in query(tbl=col_key, cols=cols[col_key]):

        obj = dict(zip(cols[col_key], e))

        if key == "destination":
            dt = {obj['destinationinfo_id']: obj['tag_id']}
        elif key == "tag":
            dt = {obj['tag_id']: obj['destinationinfo_id']}
        else:
            dt = {}
        result.append(dt)

    return result


def get_destination_info(destination_id=None):
    for row in query('vacation_destinationinfo', cols=cols['destination_info']):
        obj = dict(zip(cols['destination_info'], row))
        if destination_id == obj['id']:
            del obj["id"]
            return obj


def migrate_locality():
    for row in query('vacation_locality', cols=cols['locality']):
        obj = dict(zip(cols['locality'], row))
        oid = obj['id']
        obj['id'] = oid2nid["vacation_locality"][oid]
        obj['site_type'] = tinysite_dict.get(row[1], 0)
        location_field = 'st_asgeojson(st_astext(location))'
        obj['location'] = obj[location_field] \
                          and json.loads(obj[location_field])["coordinates"]
        del obj[location_field]
        models.Locality.objects.create(**obj)


def migrate_destination():
    for row in query('vacation_destination', cols=cols['destination']):
        obj = dict(zip(cols['destination'], row))
        oid = obj['id']
        obj['id'] = oid2nid["vacation_destination"][oid]
        obj['site_type'] = tinysite_dict.get(row[1], 0)
        location_field = 'st_asgeojson(st_astext(location))'
        obj['location'] = obj[location_field] \
                          and json.loads(obj[location_field])["coordinates"]
        del obj[location_field]

        # info_obj = {}
        # for row in query('vacation_destinationinfo', cols=cols['destination_info']):
        #     info_obj = dict(zip(cols['destination_info'], row))
        #     oid = info_obj['id']
        #     if info_obj['destination_id'] == oid:
        #         destination_tags = get_desitinationinfo_tag(key="destination")
        #         tag = oid2nid["vacation_tag"]
        #         info_obj['id'] = oid2nid["vacation_destinationinfo"][oid]
        #
        #         info_obj['tag'] = []
        #         for e in destination_tags:
        #             for k, v in e.iteritems():
        #                 if k == oid:
        #                     info_obj['tag'].append(tag[v])
        #
        # obj['info'] = info_obj
        obj['locality'] = None
        if obj['locality_id']:
            obj['locality'] = oid2nid["vacation_locality"][obj['locality_id']]
        del obj['locality_id']

        models.Destination.objects.create(**obj)



def migrate_destinationoption():
    for row in query('vacation_destinationoption', cols=cols['destination_option']):
        obj = dict(zip(cols['destination_option'], row))
        oid = obj['id']
        obj['id'] = oid2nid["vacation_destinationoption"][oid]

        obj['destination'] = oid2nid["vacation_destination"][obj['destination_id']]
        del obj['destination_id']

        obj['user'] = obj['user_id']
        del obj['user_id']

        models.DestinationOption.objects.create(**obj)


def migrate_optionmtu():
    for row in query('vacation_optionmtu', cols=cols['option_mtu']):
        obj = dict(zip(cols['option_mtu'], row))
        oid = obj['id']
        obj['id'] = oid2nid["vacation_optionmtu"][oid]

        obj['mtu'] = obj['mtu_id']
        del obj['mtu_id']

        obj['option'] = obj['option_id']
        del obj['option_id']

        models.OptionMtu.objects.create(**obj)


def migrate_tag():
    destination_tags = get_desitinationinfo_tag(key='tag')
    destination_info = oid2nid["vacation_destinationinfo"]

    for row in query('vacation_tag', cols=cols['tag']):
        obj = dict(zip(cols['tag'], row))
        oid = obj['id']
        obj['id'] = oid2nid["vacation_tag"][oid]

        obj['destination_infos'] = []
        for e in destination_tags:
            for k, v in e.iteritems():
                if k == oid:
                    obj['destination_infos'].append(destination_info[v])

        models.Tag.objects.create(**obj)


def migrate_destinationinfo():
    destination_tags = get_desitinationinfo_tag(key="destination")
    tag = oid2nid["vacation_tag"]

    for row in query('vacation_destinationinfo', cols=cols['destination_info']):
        obj = dict(zip(cols['destination_info'], row))
        oid = obj['id']
        obj['id'] = oid2nid["vacation_destinationinfo"][oid]

        obj['tags'] = []
        for e in destination_tags:
            for k, v in e.iteritems():
                if k == oid:
                    obj['tags'].append(tag[v])
        obj['destination'] = oid2nid["vacation_destination"][obj['destination_id']]
        del obj['destination_id']

        models.DestinationInfo.objects.create(**obj)


if __name__ == "__main__":
    print 'migrate locality start...'
    migrate_locality()
    print 'migrate locality end...'

    print 'migrate vacation_destinationinfo start...'
    migrate_destinationinfo()
    print 'migrate vacation_destinationinfo end...'

    print 'migrate vacation_tag start...'
    migrate_tag()
    print 'migrate vacation_tag end...'

    print 'migrate destination start...'
    migrate_destination()
    print 'migrate destination end...'

    print 'migrate destinationoption start...'
    migrate_destinationoption()
    print 'migrate destinationoption end...'

    print 'migrate optionmtu start...'
    migrate_optionmtu()
    print 'migrate optionmtu end...'
